#include "flip_internal.hpp"

LUAF(video)
{
	luaflipData& data = globalData(L);

	unsigned width = luaL_checkint(L, 1);
	unsigned height = luaL_checkint(L, 2);
	
	data.currentWindow.setMode(width, height, false);
	data.currentWindow.visible(true);
	return 0;
}

LUAF(update)
{
	luaflipData& data = globalData(L);
	bool ret = data.currentWindow.update();
	lua_pushboolean(L, ret);
	return 1;
}

LUAF(end_drawing)
{
	luaflipData& data = globalData(L);
	data.drawBuffer.flush();
	data.currentWindow.endDrawing();
	return 0;
}

LUAF(throttle_fps)
{
	luaflipData& data = globalData(L);
	int fps = luaL_checkint(L, 1);
	
	data.currentWindow.throttleFps(fps);
	return 0;
}

LUAF(next_event)
{
	luaflipData& data = globalData(L);

	if(data.currentWindow.events.empty())
		return 0;

	Flip::Event ev = data.currentWindow.events.front();
	data.currentWindow.events.pop_front();

	switch(ev.type)
	{
		case Flip::Event::Button:
		{
			lua_pushstring(L, "button");
			
			lua_createtable(L, 0, 3);
			
			lua_pushinteger(L, ev.button.id);
			lua_setfield(L, -2, "id");

			lua_pushboolean(L, ev.button.state);
			lua_setfield(L, -2, "state");
			
			lua_pushinteger(L, ev.button.character);
			lua_setfield(L, -2, "character");
			break;
		}

		default:
			return 0;
	}

	return 2;
}

LUAF(close)
{
	luaflipData& data = globalData(L);
	data.currentWindow.close();
	return 0;
}

/**/

LUAF(fsaa)
{
	luaflipData& data = globalData(L);

	int level = luaL_checkint(L, 1);
	data.currentWindow.fsaa(level);
	return 0;
}

LUAF(mouse_pos)
{
	luaflipData& data = globalData(L);

	auto pos = data.currentWindow.mousePos();
	lua_pushinteger(L, pos.x);
	lua_pushinteger(L, pos.y);
	return 2;
}